package org.lds.message.center.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import lombok.extern.slf4j.Slf4j;
import org.lds.message.center.alipay.properties.AlipayProperties;
import org.lds.message.center.common.MessageHandler;
import org.lds.message.center.common.model.request.AlipayRequest;
import org.lds.message.center.common.util.JsonUtil;

@Slf4j
public class AlipayHandler implements MessageHandler<AlipayRequest> {
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";

    private final AlipayProperties alipayProperties;
    private final AlipayClient alipayClient;

    public AlipayHandler(AlipayProperties alipayProperties) {
        this.alipayProperties = alipayProperties;

        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = alipayProperties.getEndpoint();
        config.signType = "RSA2";
        config.appId = alipayProperties.getAppId();
        config.merchantPrivateKey = alipayProperties.getAppPrivateKey();
        config.alipayPublicKey = alipayProperties.getAlipayPublicKey();
        Factory.setOptions(config);

        alipayClient = new DefaultAlipayClient(alipayProperties.getGatewayUrl(), alipayProperties.getAppId(),
                alipayProperties.getAppPrivateKey(), FORMAT, CHARSET, alipayProperties.getAlipayPublicKey(), SIGN_TYPE);
    }

    @Override
    public void handle(AlipayRequest request) throws Exception {
        AlipayTradePagePayRequest pagePayRequest = new AlipayTradePagePayRequest();
        pagePayRequest.setNotifyUrl(request.getNotifyUrl());
        pagePayRequest.setBizContent(
                "{\"out_trade_no\":\"" + request.getOutTradeNo() + "\","
                + "\"total_amount\":\"" + request.getTotalAmount() + "\","
                + "\"subject\":\"" + request.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        AlipayTradePagePayResponse response = alipayClient.pageExecute(pagePayRequest);
        log.info("支付宝支付发送成功. request={} body={}", request, JsonUtil.toJson(response));
    }
}
